#region Using

using System;
using EricWillis.Pop2Ticket.Pop3;
using WSMon.Core.Configuration;
using WSMon.Core.Interfaces;

#endregion

namespace WSMon.Core.Checkers.Mail
{
    public class Pop3Checker : Checker, IChecker
    {
        private readonly string _stringsFindToSubject = string.Empty;
        private string _logs = string.Empty;

        public Pop3Checker(EmailAccountConfiguration emailAccount, string stringsFindToSubject)
        {
            _stringsFindToSubject = stringsFindToSubject;
            EmailAccount = emailAccount;
        }

        public EmailAccountConfiguration EmailAccount { get; set; }

        #region IChecker Members

        public bool CheckOut()
        {
            if (EmailAccount == null)
            {
                _logs = "this.EmailAccount can't be null";
                return false;
            }

            try
            {
                var pop3Client = new Pop3Client(EmailAccount.UserName, EmailAccount.Password,
                                                EmailAccount.Host, EmailAccount.Port, EmailAccount.EnableSsl);

                pop3Client.Connect();
                var messages = pop3Client.GetMessages();
                foreach (var m in messages)
                {
                    if (m.Subject.Contains(_stringsFindToSubject))
                    {
                        pop3Client.DeleteMessage(m.ID);
                    }
                }
                pop3Client.Disconnect();

                return true;
            }
            catch (Exception ex)
            {
                _logs = ex.Message;
                return false;
            }
        }

        public string GetLogs()
        {
            return _logs;
        }

        #endregion
    }
}